use std::{
    collections::HashMap,
    fs,
    io::{self, BufRead},
};

/// 从资源中生成汉字->汉语拼音翻译器.
pub fn read_hanzi_resource() -> HanziToPinyinTranslator {
    let file_path = "unicode_to_hanyu_pinyin.txt";
    let file = fs::File::open(file_path).unwrap();
    let reader = io::BufReader::new(file);

    let mut result = HashMap::new();
    for line in reader.lines() {
        let line = line.unwrap();
        let parts: Vec<&str> = line.split_whitespace().collect();

        // 在这个数据里面应该恒有长度为2
        if parts.len() != 2 {
            continue;
        }

        let key = parts[0].to_string();
        let values: Vec<String> = parts[1]
            .trim_matches('(')
            .trim_matches(')')
            .split(',')
            .map(|s| s.to_string())
            .collect();
        result.insert(key, values);
    }

    HanziToPinyinTranslator::with_map(result)
}

/// 把汉字翻译成汉语拼音的翻译器.
pub struct HanziToPinyinTranslator {
    trans_map: HashMap<String, Vec<String>>,
}

impl HanziToPinyinTranslator {
    /// 使用完整数据初始化翻译器, 兼容多音字.
    pub fn with_map(map: HashMap<String, Vec<String>>) -> Self {
        Self { trans_map: map }
    }

    /// 把汉字转化成拼音, 且多音字取第一个, 并去掉音标.
    pub fn trans_hanzi_simple(&self, hanzi: char) -> Option<&str> {
        let pinyin = self.trans_hanzi(hanzi);
        pinyin.map(|pinyin| {
            let pinyin = &pinyin[0];
            &pinyin[..pinyin.len() - 1]
        })
    }

    /// 把汉字转化成拼音.
    pub fn trans_hanzi(&self, hanzi: char) -> Option<&Vec<String>> {
        let hex_hanzi = Self::string_to_hex(hanzi);
        // println!("DEBUG: hex_hanzi: {hex_hanzi}");
        self.trans_hex(&hex_hanzi)
    }

    /// 把Hex汉字转化成拼音.
    pub fn trans_hex(&self, hex_hanzi: &str) -> Option<&Vec<String>> {
        self.trans_map.get(hex_hanzi)
    }

    /// 把字符变成Hex.
    fn string_to_hex(c: char) -> String {
        format!("{:X}", c as u32)
    }
}

// mod tests {
//     #[allow(unused_imports)]
//     use super::*;

//     #[test]
//     fn test_pinyin() {
//         let hanzi_translator = read_hanzi_resource();
//         assert_eq!(
//             hanzi_translator.trans_hex("5445").unwrap(),
//             &vec!["mei2".to_string()]
//         );
//         assert_eq!(
//             hanzi_translator.trans_hanzi('则').unwrap(),
//             &vec!["ze2".to_string()]
//         );
//         assert_eq!(hanzi_translator.trans_hanzi_simple('果').unwrap(), "guo");
//         assert_eq!(hanzi_translator.trans_hanzi_simple('大').unwrap(), "da");
//     }
// }
